/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.DocumentResultController;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import model.Document;
import model.Observable;
import model.Observer;

/**
 *
 * @author Ira
 */
public class DocumentResultView extends JScrollPane implements Observer, Observable {
	
	private List<Observer> obs = new ArrayList<Observer>();
	private JTable tabResults;
	private Document[] docs = null;
	private AuthorsCellRenderer authorsRenderer = new AuthorsCellRenderer();
	private DispoCellRenderer dispoRenderer = new DispoCellRenderer();
	private DocumentResultController controller;
	private View mainWindow;
	
	public DocumentResultView(View mainWindow) {
		this.mainWindow = mainWindow;
		this.controller = new DocumentResultController(this);

		this.tabResults = new JTable(new TableDocument(this.docs));
		this.tabResults.setDefaultRenderer(List.class, this.authorsRenderer);
		this.tabResults.setDefaultRenderer(GregorianCalendar.class, this.dispoRenderer);
		this.tabResults.addMouseListener(this.controller);
		
		this.setViewportView(this.tabResults);
	}
	
	public void majResult(Document[] docs) {
		this.docs = docs;
		this.tabResults = new JTable(new TableDocument(docs));
		this.tabResults.setDefaultRenderer(List.class, this.authorsRenderer);
		this.tabResults.setDefaultRenderer(GregorianCalendar.class, this.dispoRenderer);
		this.setViewportView(this.tabResults);
		this.tabResults.addMouseListener(this.controller);
		
		this.mainWindow.setDocSearchView();
	}

	@Override
	public void update(Object items) {
		try {
			this.majResult(((Set<Document>)items).toArray(new Document[0]));
		}
		catch(ClassCastException e) {
			
		}
		catch(ArrayStoreException e2) {
			
		}
	}

	@Override
	public void addObserver(Observer obs) {
		this.obs.add(obs);
	}

	@Override
	public void updateObservers(Object data) {
		if(this.tabResults.getSelectedRow() != -1) {
			for(Observer obs: this.obs) {
				obs.update(this.docs[this.tabResults.getSelectedRow()]);
			}
		}
	}

	@Override
	public void delObserver(Observer obs) {
		this.obs.remove(obs);
	}

}
